package com.fifa.filters;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 */
public class SecurityFilter implements Filter {

    public static final String LOGGED_USER = "LOGGED_USER";
    public static final String IS_LOGGED_IN = "IS_LOGGED_IN";

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            HttpSession session = request.getSession(false);

            boolean validUser = false;
            if (session != null) {

                Boolean isLoggedIn = (Boolean) session.getAttribute(IS_LOGGED_IN);

                if (Boolean.TRUE.equals(isLoggedIn)) {
                    validUser = true;
                }
            }

            if (validUser) {
                chain.doFilter(req, resp);
            } else {
                if (session != null) {
                    session.invalidate();
                }
                response.sendRedirect("/informacion_mundialista/login.xhtml");

            }
        } catch (IOException | ServletException e) {
            Logger.getLogger(SecurityFilter.class.getName()).log(Level.SEVERE, 
                    "Error en el filtro de seguridad", e);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}
